package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import models.CategoryModel;
import models.LinkModel;

import systems.ConfigSystem;
import entities.Category;
import entities.Link;
import entities.SiteConfig;

public class CategoryServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		SiteConfig config = ConfigSystem.getConfigs();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		id = UrlHelper.getIdFromInfoUrl(id);
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Category category = categoryModel.getCategory(id);
		
		if (category == null) {
			response.sendError(404);
			return;
		}
		
		//List category children
		List<Category> categories = categoryModel.listChildren(id);
		
		//Get parent
		List<Category> parents = categoryModel.listParents(id);
		
		//Get lasetst news and paginator
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		boolean nextPage = false;
		boolean prevPage = false;
		int limit = 20;
		
		//List links
		LinkModel linkModel = LinkModel.getInstance();
		List<Link> links = linkModel.listAllByCategory(id, limit, page);
		
		request.setAttribute("category", category);
		request.setAttribute("categories", categories);
		request.setAttribute("parents", parents);
		request.setAttribute("links", links);
		try {
			request.getRequestDispatcher("/templates/" + config.getTemplate() + "/pages/category.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
